package cn.edu.ctbu.bootstrap521.restcontroller;

import cn.edu.ctbu.bootstrap521.domain.Student;
import cn.edu.ctbu.bootstrap521.helper.PageUtils;
import cn.edu.ctbu.bootstrap521.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.data.domain.Pageable;

import javax.validation.Valid;
import java.util.Collections;
import java.util.List;

@RestController
@RequestMapping(value = "/webapi/student")
@Slf4j  //产生log
public class StudentRestController {
    @Autowired
    StudentService studentService;
    /**
     * 查询全部学生信息
     * @return
     */
    @GetMapping("/list")
    public PageUtils GetAll(Integer pageSize, Integer pageNum){
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize);
        Page<Student> tempStudents = studentService.getAll(pageable);
        PageUtils pageUtils = new PageUtils(tempStudents.getTotalElements(), tempStudents.getContent());
        return pageUtils;
    }

    /**
     * 验证学号是否已存在
     * @param no
     * @return
     */
    @PostMapping("/checkDuplicateNo")
    public boolean checkDuplicateNo(@RequestParam("no") String no) {
        return studentService.existsByNo(no);
    }
    /**
     * 新增学生+后端验证
     * @param student
     * @param bindingResult
     * @return
     */
    @PostMapping("/insert")
    public int insert(@Valid Student student, BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            log.info(bindingResult.getFieldError().getDefaultMessage());
            return -1;
        }
        // 检查学号是否已存在
        if (studentService.existsByNo(student.getNo())) {
            log.info("学号已存在，请输入不同的学号！");
            return -1;
        }
        studentService.insert(student);
        Integer myid = student.getId();
        return myid.intValue();
    }
    /**
     * 按id获取学生信息
     * @param id
     * @return
     */
    @GetMapping("/get/{id}")
    public Student get(@PathVariable Integer id){
        Student student = studentService.findById(id);
        return student;
    }
    /**
     * 查询学生信息的四种方式
     * @param searchBy 查询方式：id/no/name/cno
     * @param keyword 查询关键词
     * @return ResponseEntity 包含查询结果或错误状态码
     */
    @GetMapping("/search")
    public ResponseEntity<?> searchStudents(@RequestParam String searchBy, @RequestParam String keyword) {
        switch (searchBy) {
            case "id":
                // 根据ID查询
                try {
                    Integer id = Integer.parseInt(keyword);
                    Student studentById = studentService.findById(id);
                    if (studentById != null) {
                        return ResponseEntity.ok(Collections.singletonList(studentById));
                    }
                } catch (NumberFormatException e) {
                    // ID 参数格式错误
                    return ResponseEntity.badRequest().body("ID参数格式错误");
                }
                break;
            case "no":
                // 根据学号查询
                Student studentByNo = studentService.findByNo(keyword);
                if (studentByNo != null) {
                    return ResponseEntity.ok(Collections.singletonList(studentByNo));
                } else {
                    return ResponseEntity.notFound().build(); // 返回404状态码表示未找到
                }
            case "name":
                // 根据姓名查询
                List<Student> studentsByName = studentService.searchByName(keyword);
                if (!studentsByName.isEmpty()) {
                    return ResponseEntity.ok(studentsByName);
                } else {
                    return ResponseEntity.notFound().build(); // 返回404状态码表示未找到
                }
            case "cno":
                // 根据课程号查询选课学生信息
                try {
                    Integer courseNumber = Integer.parseInt(keyword.toString());
                    List<Student> studentsByCourse = studentService.findByCourse(courseNumber);
                    if (!studentsByCourse.isEmpty()) {
                        return ResponseEntity.ok(studentsByCourse);
                    } else {
                        return ResponseEntity.notFound().build(); // 返回404状态码表示未找到
                    }
                } catch (NumberFormatException e) {
                    // cno 参数格式错误
                    return ResponseEntity.badRequest().body("课程号参数格式错误");
                }
            default:
                // 其他情况
                break;
        }
        // 如果没有找到匹配的学生信息，返回空响应
        return ResponseEntity.noContent().build();
    }
    /**
     * 更新学生
     * @param student
     * @return
     */
    @PutMapping(value = "/update")
    public Student update(Student student){
        //读取旧的数据
        Student oldstudent = studentService.findById(student.getId());
        if(StringUtils.isEmpty(student.getName())){
            //没有新姓名就用旧姓名
            student.setName(oldstudent.getName());
        }
        student = studentService.update(student);
        return student;
    }
    /**
     * 按id删除学生
     * @param id
     */
    @DeleteMapping("/delete/{id}")
    public void delete(@PathVariable Integer id){
        studentService.deleteById(id);
    }
}
